import { useRecoilCallback, useRecoilValue } from "recoil";

import {
  currentUserIdState,
  currentUserInfoQuery,
  friendsInfoQuery,
  userInfoQuery,
} from "./store";

export default function CurrentUserInfo() {
  const currentUser = useRecoilValue(currentUserInfoQuery);
  const friends = useRecoilValue(friendsInfoQuery);

  // Note that this pre-fetching works by triggering the `selectorFamily()` to
  // initiate an async query and populate the selector's cache. If you are
  // using an `atomFamily()` instead, by either setting the atoms or relying on
  // atom effects to initialize, then you should use useRecoilTransaction_UNSTABLE()
  // instead of `useRecoilCallback()`, as trying to set the state of the provided
  // `Snapshot` will have no effect on the live state in the host `<RecoilRoot>`.
  const changeUser = useRecoilCallback(({ snapshot, set }) => (userId) => {
    snapshot.getLoadable(userInfoQuery(userId)); // pre-fetch user info
    set(currentUserIdState, userId); // change current user to start new render
  });

  return (
    <div>
      <h1>With Suspense</h1>
      <h2>{currentUser.name}</h2>
      <ul>
        {friends.map((friend) => (
          <li key={friend.id} onClick={() => changeUser(friend.id)}>
            {friend.name}
          </li>
        ))}
      </ul>
    </div>
  );
}
